import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileUtil {
    private static final String USER_FILE = "users.txt";
    private static final String MOVIE_FILE = "movies.txt";
    private static final String HALL_FILE = "halls.txt";
    private static final String SHOW_FILE = "shows.txt";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 用户数据读写
    public static List<User> readUsers() {
        List<User> users = new ArrayList<>();
        File file = new File(USER_FILE);
        if (!file.exists()) return users;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length != 8) continue;

                String id = parts[0];
                String username = parts[1];
                String password = parts[2];
                String phone = parts[3];
                String userType = parts[4];
                Date registerTime;
                int loginAttempts = Integer.parseInt(parts[6]);
                boolean locked = Boolean.parseBoolean(parts[7]);

                try {
                    registerTime = sdf.parse(parts[5]);
                } catch (ParseException e) {
                    registerTime = new Date();
                }

                User user = switch (userType) {
                    case "管理员" -> new Admin(id, username, password, phone);
                    case "经理" -> new Manager(id, username, password, phone);
                    case "前台" -> new FrontDesk(id, username, password, phone);
                    default -> null;
                };

                if (user != null) {
                    user.registerTime = registerTime;
                    user.loginAttempts = loginAttempts;
                    user.locked = locked;
                    users.add(user);
                }
            }
        } catch (IOException e) {
            System.err.println("读取用户文件失败: " + e.getMessage());
        }
        return users;
    }

    public static void writeUsers(List<User> users) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(USER_FILE))) {
            for (User user : users) {
                String line = String.join(",",
                        user.getId(),
                        user.getUsername(),
                        user.password,
                        user.getPhone(),
                        user.getUserType(),
                        sdf.format(user.getRegisterTime()),
                        String.valueOf(user.loginAttempts),
                        String.valueOf(user.locked)
                );
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("写入用户文件失败: " + e.getMessage());
        }
    }

    // 电影数据读写
    public static List<Movie> readMovies() {
        List<Movie> movies = new ArrayList<>();
        File file = new File(MOVIE_FILE);
        if (!file.exists()) return movies;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length != 7) continue;

                movies.add(new Movie(
                        parts[0],
                        parts[1],
                        parts[2],
                        parts[3],
                        parts[4],
                        Integer.parseInt(parts[5]),
                        Double.parseDouble(parts[6])
                ));
            }
        } catch (IOException e) {
            System.err.println("读取电影文件失败: " + e.getMessage());
        }
        return movies;
    }

    public static void writeMovies(List<Movie> movies) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(MOVIE_FILE))) {
            for (Movie movie : movies) {
                String line = String.join(",",
                        movie.getId(),
                        movie.getName(),
                        movie.getDirector(),
                        movie.getActors(),
                        movie.getIntroduction(),
                        String.valueOf(movie.getDuration()),
                        String.valueOf(movie.getRating())
                );
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("写入电影文件失败: " + e.getMessage());
        }
    }

    // 放映厅数据读写
    public static List<Hall> readHalls() {
        List<Hall> halls = new ArrayList<>();
        File file = new File(HALL_FILE);
        if (!file.exists()) return halls;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(";");
                if (parts.length != 4) continue;

                String id = parts[0];
                String name = parts[1];
                int rows = Integer.parseInt(parts[2]);
                Hall hall = new Hall(id, name, rows, 0);
                hall.getSeats().clear();

                // 解析座位信息
                String[] seatParts = parts[3].split("\\|");
                for (String seatStr : seatParts) {
                    if (seatStr.isEmpty()) continue;
                    String[] s = seatStr.split(",");
                    if (s.length != 4) continue;

                    Seat seat = new Seat(s[0], Integer.parseInt(s[1]), Integer.parseInt(s[2]));
                    seat.setSold(Boolean.parseBoolean(s[3]));
                    hall.getSeats().add(seat);
                }
                halls.add(hall);
            }
        } catch (IOException e) {
            System.err.println("读取放映厅文件失败: " + e.getMessage());
        }
        return halls;
    }

    public static void writeHalls(List<Hall> halls) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(HALL_FILE))) {
            for (Hall hall : halls) {
                // 拼接座位信息
                StringBuilder seatsStr = new StringBuilder();
                for (Seat seat : hall.getSeats()) {
                    seatsStr.append(seat.getId()).append(",")
                            .append(seat.getRow()).append(",")
                            .append(seat.getCol()).append(",")
                            .append(seat.isSold()).append("|");
                }

                String line = String.join(";",
                        hall.getId(),
                        hall.getName(),
                        String.valueOf(hall.getRows()),
                        seatsStr.toString()
                );
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("写入放映厅文件失败: " + e.getMessage());
        }
    }

    // 场次数据读写
    public static List<Show> readShows(List<Movie> movies, List<Hall> halls) {
        List<Show> shows = new ArrayList<>();
        File file = new File(SHOW_FILE);
        if (!file.exists()) return shows;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length != 5) continue;

                String id = parts[0];
                Movie movie = movies.stream()
                        .filter(m -> m.getId().equals(parts[1]))
                        .findFirst().orElse(null);
                Hall hall = halls.stream()
                        .filter(h -> h.getId().equals(parts[2]))
                        .findFirst().orElse(null);
                Date showTime;
                double price = Double.parseDouble(parts[4]);

                if (movie == null || hall == null) continue;
                try {
                    showTime = DateUtil.parse(parts[3]);
                } catch (IllegalArgumentException e) {
                    continue;
                }

                shows.add(new Show(id, movie, hall, showTime, price));
            }
        } catch (IOException e) {
            System.err.println("读取场次文件失败: " + e.getMessage());
        }
        return shows;
    }

    public static void writeShows(List<Show> shows) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(SHOW_FILE))) {
            for (Show show : shows) {
                String line = String.join(",",
                        show.getShowId(),
                        show.getMovie().getId(),
                        show.getHall().getId(),
                        DateUtil.format(show.getShowTime()),
                        String.valueOf(show.getPrice())
                );
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            System.err.println("写入场次文件失败: " + e.getMessage());
        }
    }
}